import React from 'react'
import PropTypes from 'prop-types'
import cssStyle from './index.module.css'

class RadioGroup extends React.PureComponent{
    onChange = value => {
        if(this.props.onChange){
            this.props.onChange(value)
        }
    }
    render(){
        let invalidStyle = {}
        if(this.props.invalid){
            invalidStyle.border = '1px solid red'
        }
        return(
            <div style={{padding: '8px 0', borderRadius: '4px', ...invalidStyle, ...this.props.style }}>
                {
                    React.Children.map(this.props.children, item => {
                        if(item){
                            let checked = this.props.value == item.props.value ? true : false
                            return React.cloneElement(item, {
                                checked,
                                onChange: this.onChange
                            })
                        }
                    })
                }
            </div>
        )
    }
}

RadioGroup.propTypes = {
    onChange: PropTypes.func,
    children: PropTypes.oneOfType([PropTypes.object, PropTypes.array]),
    value: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
    invalid: PropTypes.bool,
    style: PropTypes.object
}

class Radio extends React.PureComponent{
    onChange(value){
        this.props.onChange(value)
    }
    render(){
        let value = ((typeof this.props.value === 'string') || (typeof this.props.value === 'number')) ? this.props.value : ''
        return(
            <div className={ cssStyle.radio }>
                <label>
                    <span className={ cssStyle.checkbox + ' ' + (this.props.checked ? cssStyle.checked : '') }>
                        <span className={ cssStyle.radioInner }></span>
                        <input
                            {...this.props}
                            type="radio"
                            value={ value }
                            checked={ this.props.checked }
                            onChange={ (e => { this.onChange(e.target.value) }).bind(this) }
                            className={ this.props.disabled ? cssStyle.disabled : '' }
                        />
                    </span>
                    <span className={ this.props.disabled ? cssStyle.disabled : '' } style={{ color: this.props.checked ? '#409eff' : '#000', marginLeft: '8px' }}>{ this.props.label }</span>
                </label>
            </div>
        )
    }
}

Radio.propTypes = {
    onChange: PropTypes.func,
    value: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
    label: PropTypes.string,
    checked: PropTypes.bool,
    disabled: PropTypes.bool
}

export {
    RadioGroup,
    Radio
}